package edu.washington.vaccine.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import edu.washington.vaccine.R;
import edu.washington.vaccine.backend.Patient;
import edu.washington.vaccine.backend.Vaccine;
import edu.washington.vaccine.backend.VaccineDB;
import edu.washington.vaccine.backend.VaccineLocalHelper;


/*
 * 
 * Permits user to edit previously added patient data
 * and update the patient contents
 */
public class EditPatientActivity extends Activity {
	@SuppressWarnings("unused")
	private static final String TAG = "EditPatientActivity";
	private Context context;
	private int checkPointer;
	private OnDateSetListener odsl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form);
		this.context = this;
		TextView title = (TextView) findViewById(R.id.title);
		title.requestFocus();
		title.setText(R.string.edit_patient);

		Bundle data = getIntent().getExtras();
		final Patient p = (Patient) data.getSerializable("patient");

		// Pasting the current data on the form
		((EditText) findViewById(R.id.idNumber)).setText("" + p.id);
		((EditText) findViewById(R.id.idNumber)).setKeyListener(null);

		((EditText) findViewById(R.id.firstName)).setText(p.fname);
		((EditText) findViewById(R.id.lastName)).setText(p.lname);
		DatePicker d = (DatePicker) findViewById(R.id.birthdate);
		String[] date = p.dob.split("-");
		d.init(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]), DateLimiter.getInstance());
		((EditText) findViewById(R.id.birthplace)).setText("" + p.location);
		((EditText) findViewById(R.id.motherName)).setText(p.mother);
		((EditText) findViewById(R.id.fatherName)).setText(p.father);
		//		((EditText) findViewById(R.id.vaccinesReceived)).setText(p.vaccineInfo);

		checkPointer = 0;

		odsl=new OnDateSetListener() {
			public void onDateSet(DatePicker date, int year, int month, int dayOfMonth) {
				TextView text = (TextView) findViewById(checkPointer);
				String birthdate = "";
				month++;
				if (month < 10)
					birthdate = "0";
				birthdate += month + "-";

				if (dayOfMonth < 10)
					birthdate += "0";
				birthdate += dayOfMonth + "-" + year;

//				 text.setText("    " + month + "-" + dayOfMonth + "-" + year);
				text.setText(birthdate);
			}
		};

		createTable(p);
		Button editButton = (Button) findViewById(R.id.button1);
		editButton.setText(R.string.save);

//		if (VaccineDB.getInstance().isOnlineMode()) {
//			editButton.setOnClickListener(new SendDataListener(
//					this, true, PatientDataActivity.class, "patientdata"));
//		} else {
//			editButton.setOnClickListener(new SendDataListener(
//					this, false, PatientDataActivity.class, "patientdata"));
//		}
		
		editButton.setOnClickListener(new SendDataListener(
				this, VaccineDB.getInstance().isOnlineMode(), PatientDataActivity.class, "patientdata"));

		Button cancelButton = (Button) findViewById(R.id.button2);
		cancelButton.setText(R.string.cancel);
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				Intent i = new Intent(context, PatientDataActivity.class);
//				i.putExtra("patient", p); 
//				startActivity(i);
//				finish();
				FirstGroup.group.back();
			}			
		});
	}

	private void createTable(Patient p) {

		final List<Vaccine> pArray = new ArrayList<Vaccine>();
		VaccineLocalHelper localDB = VaccineLocalHelper.getInstance(this);
		LinearLayout l = (LinearLayout) findViewById(R.id.oldvaccine);
		Cursor cursor = localDB.getReadableDatabase().rawQuery("SELECT * FROM Vaccines", new String [] {});
		startManagingCursor(cursor);
		// collect data from local database 
		ScrollView sv = new ScrollView(this);
		sv.setId(R.string.old_vaccine_listing);
		TableLayout tl = new TableLayout(this);
		sv.addView(tl);
		Map<Integer, String> findVacc = getVaccineHistory(context, "" + p.id);
		
		while (cursor.moveToNext()) {
			int vid = cursor.getInt(0);
			String vname = cursor.getString(1);
//			int vdose = cursor.getInt(2);
			String vdesc = cursor.getString(2);
			String vschedule = cursor.getString(3);
			pArray.add(new Vaccine(vid, vname, vdesc, vschedule));
		}
		cursor.close();

		for(Vaccine v : pArray) {
			TableRow tr = new TableRow(this);
			CheckBox chk = new CheckBox(this);
			final TextView date = new TextView(this);
			chk.setTextColor(R.color.black);
			chk.setText(v.name);
			date.setId(v.id);
			if(findVacc.containsKey(v.id)){
				chk.setChecked(true);
				date.setText("   " + findVacc.get(v.id));
			}
			chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					checkPointer = date.getId();
					if(isChecked) {
						Calendar cal=Calendar.getInstance();
						DatePickerDialog datePickDiag = new DatePickerDialog(getParent().getParent(),
								odsl,cal.get(Calendar.YEAR),
								cal.get(Calendar.MONTH),
								cal.get(Calendar.DAY_OF_MONTH));
						datePickDiag.show();
					}
					else {
						TextView text = (TextView) findViewById(checkPointer);
						text.setText("");
					}
				}
			});
			tr.addView(chk);
			tr.addView(date);
			tl.addView(tr);
		}
		l.addView(sv);
	}

	private static Map<Integer, String> getVaccineHistory(Context context, String pid) {
		VaccineDB db = VaccineDB.getInstance();
		VaccineLocalHelper helper = VaccineLocalHelper.getInstance(context);
		Map<Integer, String> findVacc = new HashMap<Integer, String>();
		Set<String[]> vaccines;
		if (db.isOnlineMode()) {
			vaccines = db.getPatientsVaccines("" + pid);
		}
		else {
			vaccines = helper.getPatientsVaccinesWithId(pid);
		}
		if (vaccines != null) {
			for (String[] s : vaccines) {
				findVacc.put(Integer.parseInt(s[0]), s[1]);
			}
		}
		return findVacc;
	}


	@Override
	public void onBackPressed() {
		//		Intent i = new Intent(this, VaccineActivity.class);
		//		VaccineActivity parentActivity = (VaccineActivity)getParent();
		//		parentActivity.replaceContentView("nextactivity", i);
		FirstGroup.group.back();
	}
}
